import { createApp, toRaw } from 'vue'
import './style.css'
import App from './App.vue'
import {router} from './router/index'
import { createPinia } from 'pinia'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import PanelHead from './components/panelHead.vue'
import { useStore } from './store/store'

// 路由守卫
router.beforeEach((to, from) => {
  const token = localStorage.getItem('pz_token')
  // 非登录页面不存在token
  if (!token && to.path !== '/login') {
    return '/login'
  } else if (token && to.path === '/login') {
    return '/'
  } else {
    return true
  }
})

// 创建app
const app = createApp(App)

app.component('PanelHead', PanelHead)
// 注册element-plus图标
for(const [key, component] of Object.entries(ElementPlusIconsVue)){
  app.component(key, component)
}

// 使用路由
app.use(router)
// 使用 pinia 
app.use(createPinia())

const store = useStore()
// 获取本地存储的菜单数据
// const localData = localStorage.getItem('routerList')
// if (localData) {
//   store.dynamicMenu(store.routerList)
//   toRaw(store.routerList).forEach((item) => {
//     router.addRoute('Home', item)
//   })
// }

const localData = localStorage.getItem('routerList')
if (localData) {
  try {
    const menuData = JSON.parse(localData)
    store.dynamicMenu(menuData)
    toRaw(store.routerList).forEach((item) => {
      router.addRoute('Home', item)
    })
  } catch (error) {
    console.error('路由数据解析错误:', error)
    localStorage.removeItem('routerList') // 清除无效数据
  }
}

// console.log(router)

app.mount('#app')






